package cn.wujiangbo.controller.app;

import cn.wujiangbo.constants.Constants;
import cn.wujiangbo.domain.app.AppUser;
import cn.wujiangbo.mapper.app.AppUserMapper;
import cn.wujiangbo.result.PageList;
import cn.wujiangbo.exception.MyException;
import cn.wujiangbo.service.app.AppUserService;
import cn.wujiangbo.query.app.AppUserQuery;
import cn.wujiangbo.annotation.CheckPermission;
import cn.wujiangbo.result.JSONResult;
import cn.wujiangbo.annotation.MyLog;
import cn.wujiangbo.enums.BusinessType;
import cn.wujiangbo.controller.base.BaseController;
import cn.wujiangbo.utils.DateUtils;
import cn.wujiangbo.utils.file.FileUploadUtils;
import cn.wujiangbo.utils.poi.ExcelUtil;
import cn.wujiangbo.constants.ErrorCode;
import cn.wujiangbo.vo.system.UploadFileVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author 波波老师(weixin : javabobo0513)
 * @desc APP用户信息表 API接口
 * @date 2024-05-10
 */
@RestController
@RequestMapping("/appUser")
public class AppUserController extends BaseController {

    @Resource
    public AppUserService appUserService;

    @Resource
    public AppUserMapper appUserMapper;

    /**
     * 新增数据到【APP用户信息表】
     *
     * @date 2024-05-10
     */
    @PostMapping(value = "/save")
    @CheckPermission(per = "appUser:save")
    @MyLog(title = "新增数据到【APP用户信息表】", businessType = BusinessType.INSERT)
    public JSONResult save(@RequestBody AppUser appUser) {
        appUser.setCreateTime(DateUtils.getCurrentLocalDateTime());
        appUser.setCreateUserId(getUserId());
        appUser.setCreateUserName(getUserName());
        appUser.setUpdateTime(DateUtils.getCurrentLocalDateTime());
        appUser.setUpdateUserId(getUserId());
        appUser.setUpdateUserName(getUserName());
        appUserService.save(appUser);
        return JSONResult.success(true);
    }

    /**
     * 删除【APP用户信息表】数据
     *
     * @date 2024-05-10
     */
    @PostMapping(value = "/batchDelete")
    @MyLog(title = "删除【APP用户信息表】数据", businessType = BusinessType.DELETE)
    @CheckPermission(per = "appUser:deleteBatch")
    public JSONResult batchDelete(@RequestBody AppUserQuery query) {
        if (query.getIds() == null) {
            throw new MyException(ErrorCode.COMMON_CODE_2001);
        }

        //删除业务数据时，阿里云OSS中的图片也需要一起删掉，节省空间
        List<String> ossFullPathList = new ArrayList<>();
        List<AppUser> listData = appUserMapper.selectBatchIds(Arrays.asList(query.getIds()));
        if (listData != null && listData.size() > 0) {
            for (int i = 0; i < listData.size(); i++) {
                ossFullPathList.add(listData.get(i).getUserImg());
            }
        }
        fileUploadUtils.deleteFileFromOss(ossFullPathList);
        //删除数据库数据
        appUserService.removeByIds(Arrays.asList(query.getIds()));
        return JSONResult.success(true);
    }

    /**
     * 修改【APP用户信息表】表数据
     *
     * @date 2024-05-10
     */
    @PostMapping(value = "/update")
    @MyLog(title = "修改【APP用户信息表】表数据", businessType = BusinessType.UPDATE)
    @CheckPermission(per = "appUser:update")
    public JSONResult update(@RequestBody AppUser appUser) {
        appUser.setUpdateTime(DateUtils.getCurrentLocalDateTime());
        appUser.setUpdateUserId(getUserId());
        appUser.setUpdateUserName(getUserName());
        appUserService.updateById(appUser);
        return JSONResult.success(true);
    }

    /**
     * 查询【APP用户信息表】数据（分页）
     *
     * @param query 查询对象
     * @return PageList 分页对象
     * @date 2024-05-10
     */
    @PostMapping(value = "/pagelist")
    @MyLog(title = "查询【APP用户信息表】数据（分页）", businessType = BusinessType.QUERY)
    @CheckPermission(per = "appUser:pagelist")
    public JSONResult pagelist(@RequestBody AppUserQuery query) {
        Page<AppUser> page = appUserService.selectMySqlPage(query);
        return JSONResult.success(new PageList<>(page.getTotal(), page.getRecords()));
    }

    /**
     * 查询【APP用户信息表】数据（不分页）
     *
     * @date 2024-05-10
     */
    @GetMapping(value = "/list")
    @MyLog(title = "查询【APP用户信息表】数据（不分页）", businessType = BusinessType.QUERY)
    public JSONResult list() {
        QueryWrapper<AppUser> queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("id");//根据ID降序排序，最新的数据展示在最上面
        List<AppUser> list = appUserService.list(queryWrapper);
        return JSONResult.success(list);
    }

    /**
     * 根据ID查询【APP用户信息表】数据
     *
     * @date 2024-05-10
     */
    @GetMapping(value = "/getDataById/{id}")
    @MyLog(title = "根据ID查询【APP用户信息表】数据", businessType = BusinessType.QUERY)
    public JSONResult getDataById(@PathVariable("id") Long id) {
        return JSONResult.success(appUserService.getById(id));
    }

    /**
     * 根据 QueryWrapper 对象查询【APP用户信息表】数据
     *
     * @date 2024-05-10
     */
    @GetMapping(value = "/queryWrapper/{objName}")
    public JSONResult queryWrapper(@PathVariable("objName") String objName) {
        QueryWrapper<AppUser> queryWrapper = new QueryWrapper();
        queryWrapper.eq("", objName);
        AppUser one = appUserService.getOne(queryWrapper);
        return JSONResult.success(one);
    }

    /**
     * 【APP用户信息表】数据导出Excel
     */
    @PostMapping(value = "/exportExcelFile")
    @CheckPermission(per = "appUser:exportExcelFile")
    @MyLog(title = "【APP用户信息表】数据导出Excel", businessType = BusinessType.EXPORT)
    public void exportExcelFile(HttpServletResponse response, AppUserQuery query) {
        List<AppUser> list = appUserService.selectExportExcelData(query);
        ExcelUtil<AppUser> util = new ExcelUtil<>(AppUser.class);
        util.exportExcel(response, list, "APP用户信息表");
    }

    /**
     * xxx操作
     */
    @PostMapping(value = "/xxxHandle")
    @MyLog(title = "xxxxxxxxxx", businessType = BusinessType.UPDATE)
    @CheckPermission(per = "xxxxxx:xxxxxx")
    public JSONResult xxxHandle(@RequestBody AppUser appUser) {
        AppUser obj = appUserService.getById(appUser.getId());
        if (obj == null) {
            throw new MyException(ErrorCode.COMMON_CODE_2001);
        }
        //做其他操作
        appUserService.updateById(obj);
        return JSONResult.success(true);
    }

    /***********************************************************************************
     以上代码是自动生成的
     自己写的代码放在下面
     ***********************************************************************************/

    @Resource
    private FileUploadUtils fileUploadUtils;

    /**
     * APP查询个人资料
     *
     * @param userId 用户ID
     */
    @GetMapping(value = "/getUserInfoById/{userId}")
    public JSONResult getUserInfoById(@PathVariable("userId") Long userId) {
        if (userId == null || userId == -1) {
            throw new MyException("入参ID错误！");
        }
        QueryWrapper<AppUser> queryWrapper = new QueryWrapper();
        queryWrapper.eq("id", userId);
        AppUser one = appUserService.getOne(queryWrapper);
        if (one == null) {
            throw new MyException("用户信息不存在！");
        }
        return JSONResult.success(one);
    }

    /**
     * 更换头像接口
     *
     * @param file 文件对象
     */
    @PostMapping("/uploadUserImg")
    public JSONResult imageMission(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            throw new MyException("上传的图片为空！");
        }
        UploadFileVo vo = fileUploadUtils.fileUploadOss(Constants.OSS.RESOURCE_LINK_IMG, file);
        String filePath = vo.getFilePrefix() + vo.getFileName();
        System.out.println("上传头像保存路径=" + filePath);
        //修改个人头像资料
        Long appUserId = getAppUserId();
        if (appUserId == null || appUserId == -1) {
            throw new MyException("用户信息错误，请重新登录！");
        }
        AppUser user = appUserService.getById(appUserId);
        user.setUserImg(filePath);
        appUserService.updateById(user);
        return JSONResult.success(true);
    }

    /**
     * APP端-修改个人资料
     */
    @PostMapping(value = "/updateUserInfo")
    public JSONResult updateUserInfo(@RequestBody AppUser appUser) {
        if (appUser.getId() == null) {
            throw new MyException("用户ID错误！");
        }
        AppUser one = appUserService.getById(appUser.getId());
        if (one == null) {
            throw new MyException("用户信息不存在！");
        }

        //手机号不能重复
        QueryWrapper<AppUser> queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_phone", appUser.getUserPhone());
        AppUser phoneOne = appUserService.getOne(queryWrapper);
        if (phoneOne != null && !Objects.equals(phoneOne.getId(), one.getId())) {
            throw new MyException("手机号码已存在，请更换！");
        }

        //昵称不能重复
        QueryWrapper<AppUser> queryWrapper2 = new QueryWrapper();
        queryWrapper2.eq("nick_name", appUser.getNickName());
        AppUser nickNameOne = appUserService.getOne(queryWrapper2);
        if (nickNameOne != null && !Objects.equals(nickNameOne.getId(), one.getId())) {
            throw new MyException("用户昵称已存在，请更换！");
        }

        //身份证号不能重复
        QueryWrapper<AppUser> queryWrapper3 = new QueryWrapper();
        queryWrapper3.eq("id_no", appUser.getIdNo());
        AppUser idNoOne = appUserService.getOne(queryWrapper3);
        if (idNoOne != null && !Objects.equals(idNoOne.getId(), one.getId())) {
            throw new MyException("身份证号已存在，请更换！");
        }

        one.setUpdateTime(DateUtils.getCurrentLocalDateTime());
        one.setUserPhone(appUser.getUserPhone());
        one.setNickName(appUser.getNickName());
        one.setIdNo(appUser.getIdNo());
        one.setUserSex(appUser.getUserSex());
        appUserService.updateById(one);
        return JSONResult.successMessage(true, "个人资料更新成功！");
    }

    /**
     * APP端-重置密码
     */
    @PostMapping(value = "/resetPassword")
    public JSONResult resetPassword(@RequestBody AppUser appUser) {
        QueryWrapper<AppUser> queryWrapper = new QueryWrapper();
        queryWrapper.eq("login_name", appUser.getLoginName());
        AppUser one = appUserService.getOne(queryWrapper);
        if (one == null) {
            throw new MyException("该账号不存在！");
        }
        one.setLoginPass(appUser.getLoginPass());//设置密码
        appUserService.updateById(one);
        return JSONResult.successMessage(true, "密码重置成功！");
    }


}